package com.zhangxiaofanfan.hotcode.second;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

/**
 * <a href="https://leetcode.cn/problems/group-anagrams/description/?envType=study-plan-v2&envId=top-100-liked">字母异位词分组</a>
 *
 * @author zhangxiaofanfan
 * @date 2024-05-20 22:59:42
 */
public class HotCode002 {
    public static void main(String[] args) {
        String[] strs = {"bur", "rub", "aaa"};
        HotCode002 hotCode002 = new HotCode002();
        hotCode002.groupAnagrams(strs).forEach(System.out::println);
    }

    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            Map<Character, Integer> temp = new TreeMap<>(Character::compare);
            for (char c : str.toCharArray()) {
                temp.put(c, temp.getOrDefault(c, 0) + 1);
            }
            StringBuffer stringBuffer = new StringBuffer();
            temp.keySet().forEach(key -> stringBuffer.append(key).append(temp.get(key)));
            if (!map.containsKey(stringBuffer.toString())) {
                map.put(stringBuffer.toString(), new ArrayList<>());
            }
            map.get(stringBuffer.toString()).add(str);
        }
        return map.values().stream().toList();
    }

}
